package generadorDescriptores.dom;

import java.util.ArrayList;

import generadorDescriptores.AttributesData;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class JoinsDom {
	private Element joins;
	private Document document; 
	private ArrayList<JoinDom> joinList;
	
	public JoinsDom(Document doc){
		this.document = doc;
		this.joins = doc.createElement("joins");
		this.joinList = new ArrayList<JoinDom>();
	}
	
	public void addJoin(JoinDom join){
		this.joins.appendChild(join.getElement());
		this.joinList.add(join);
	}

	public Element getElement() {
		return this.joins;
	}
	
	private JoinDom getJoinByName(String joinName){
		JoinDom join = null;
		for (int i = 0; i < joinList.size(); i++) {
			if (joinList.get(i).getElement().getAttributes().getNamedItem("name").getNodeValue().equals(joinName)){
				join = joinList.get(i);
			}
		}
		return join;
	}
	
	private JoinDom addNewJoin(AttributesData data){
		JoinDom join = new JoinDom(this.document);
		join.setAttributes(data.getJoinName(), data.getJoinTable());
		this.addJoin(join);
		return join;
	}
	
	public void addConditionToJoin(String joinName, AttributesData data){
		JoinDom join = getJoinByName(joinName);
		if (join == null){
			join = addNewJoin(data);
		}
		join.addCondition(data);		
	}
	
	

}
